/**
 * Created by Administrator on 2018/12/13.
 */
var express = require('express');
var router = express.Router();
var db = require('../../../libs/mysql');
//统一返回格式
var res_Data;
router.use( function(req, res, next) {
    res_Data = {
        code: 0,
        message: ''
    }
    next();
});

router.get('/',function (req,res) {
    var reviewid = req.query.contentid || '';
    var num = req.query.num || '';
    db.query(`select count(*) from comments WHERE reviewid=${reviewid}`,(err,count)=>{
        if(err){
            res.send('总条数查询').end();
        }else {
            var count = count[0]['count(*)'];
            if(num>=count){
                num=count;
            }
            var sql = 'SELECT u.nickname,t.* FROM comments t LEFT JOIN user u ON t.userid = u.id WHERE t.reviewid='+reviewid+' order by id desc limit ' + num;
            db.query(sql,(err,data)=>{
                if(err){
                    res.send("评论列表显示").end();
                }else {
                    res_Data.num = num;
                    res_Data.count = count;
                    res_Data.data = data;
                    res.json(res_Data);
                    return;
                }
            })
        }
    })
});
router.post('/',(req,res)=>{
    var reviewid = req.body.contentid || '',//文章id
        contents = req.body.contents,
        userid = req.userInfo.id;
    db.query(`INSERT INTO comments (reviewid, comments, userid) VALUES (${reviewid},'${contents}',${userid})`,(err,data)=>{
        if(err){
            res.send('评论插入').end();
        }else {
            res_Data.message = '评论成功';
            res.json(res_Data);
            return;
        }
    })
})


module.exports = router;